<template>
  <main>
    <el-form
      ref="ruleFormRef"
      label-width="auto"
      :model="data.form"
      :rules="data.rules"
      v-loading="data.load"
      status-icon
    >
      <el-form-item label="项目A" prop="pathA">
        <el-input v-model="data.form.pathA" placeholder="请输入项目A路径">
        </el-input>
      </el-form-item>
      <el-form-item label="项目B" prop="pathA">
        <el-input v-model="data.form.pathB" placeholder="请输入项目B路径">
        </el-input>
      </el-form-item>
      <el-form-item label="操作">
        <el-button type="primary" @click="submitForm(ruleFormRef)">检查</el-button>
        <el-button type="success" @click="onSave(ruleFormRef)">保存</el-button>
      </el-form-item>
    </el-form>
<!-- 
    <el-form-item label="项目B" prop="language">
        <el-select v-model="codeData.language" placeholder="请选择语言">
          <el-option label="JavaScript" value="javascript"></el-option>
          <el-option label="CSS" value="css"></el-option>
          <el-option label="HTML" value="html"></el-option>
          <el-option label="JSON" value="json"></el-option>
        </el-select>
    </el-form-item> -->

    <!-- <EditCode v-model:value="codeData.codeA" v-model:language="codeData.languageA" /> -->


    <el-dialog v-model="codeData.show" title="代码对比" width="80vw">
      <el-row style="width:100%;" :gutter="12">
        <template v-if="!codeData.load">
          <el-col :span="codeData.hideB ? 24 : 12" style="width:100%;position: relative;">
            <el-divider content-position="left">项目A:{{ codeData.fileA }}</el-divider>
            <el-select v-model="codeData.languageA" placeholder="请选择语言">
              <el-option v-for="item,key in languageOptions" :key="key" :label="item" :value="key" />
            </el-select>
            <EditCode v-model:value="codeData.codeA" v-model:language="codeData.languageA" h="50vh" :lines="codeData.linesA"/>
          </el-col>
          <el-col v-if="!codeData.hideB" :span="12" style="width:100%;position: relative;">
            <el-divider content-position="left">项目B:{{ codeData.fileB }}</el-divider>
            <el-select v-model="codeData.languageB" placeholder="请选择语言">
              <el-option v-for="item,key in languageOptions" :key="key" :label="item" :value="key" />
            </el-select>
            <EditCode v-model:value="codeData.codeB" v-model:language="codeData.languageB" h="50vh" :lines="codeData.linesB"/>
          </el-col>
        </template>
        <div v-else style="text-align:center;margin:0 auto;width:60%;height:50vh;" v-loading="codeData.load">
          <el-empty description="加载中..." />
        </div>
      </el-row>
    </el-dialog>
    
    <template v-if="data.ProjectView">
      <el-divider content-position="left">比较如下：</el-divider>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-card header="项目A">
            <template #header>
              项目A 文件数：&nbsp;<el-tag>{{ projectInfo.ProjectA.FileLimit }}</el-tag>&nbsp;&nbsp;文件夹数：&nbsp;<el-tag type="danger">{{ projectInfo.ProjectA.DirLimit }}</el-tag>
              &nbsp;滚动高度&nbsp;<el-input-number :min="100" :max="1080" :step="20" v-model="data.ProjectAHeight" placeholder="高度" />px
            </template>
            <el-divider content-position="center">特有文件：<el-tag>{{ projectInfo.AddFileA.length }}</el-tag></el-divider>
            <el-row :style="`overflow-y: auto;height: ${data.ProjectAHeight}px;`" class="result">
              <template v-for="item,key in projectInfo.AddFileA" :key="key">
                <el-col @click="onChangeProjectFile(item.Name, true)" :xs="18" :sm="18" :md="18" :lg="10" :xl="10"><el-tag type="warning" >{{ item.Name }}</el-tag></el-col>
                <el-col :xs="6" :sm="6" :md="6" :lg="4" :xl="4"><el-tag type="success">{{ Math.floor(item.Size / 1024 * 100) / 100 }}KB</el-tag></el-col>
                <el-col :xs="18" :sm="18" :md="18" :lg="6" :xl="6"><el-tag type="info">{{ new Date(item.UpdatedAt * 1000).toLocaleString() }}</el-tag></el-col>
                <el-col :xs="6" :sm="6" :md="6" :lg="4" :xl="4"><el-tag>{{ item.IsDir ? '文件夹' : '文件' }}</el-tag></el-col>
              </template>
            </el-row>
            <el-divider content-position="center">修改文件：<el-tag>{{ projectInfo.ChangeFile.length }}</el-tag></el-divider>
            <el-row :style="`overflow-y: auto;height: ${data.ProjectAHeight}px;`" class="result">
              <template v-for="item,key in projectInfo.ChangeFile" :key="key" >
                <el-col @click="onChangeProjectFile(item.Name)" :xs="18" :sm="18" :md="18" :lg="10" :xl="10"><el-tag type="warning" >{{ item.Name }}</el-tag></el-col>
                <el-col :xs="6" :sm="6" :md="6" :lg="4" :xl="4"><el-tag type="success">{{ Math.floor(item.Size / 1024 * 100) / 100 }}KB</el-tag></el-col>
                <el-col :xs="18" :sm="18" :md="18" :lg="6" :xl="6"><el-tag type="info">{{ new Date(item.UpdatedAt * 1000).toLocaleString() }}</el-tag></el-col>
                <el-col :xs="6" :sm="6" :md="6" :lg="4" :xl="4"><el-tag>{{ item.IsDir ? '文件夹' : '文件' }}</el-tag></el-col>
              </template>
            </el-row>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card header="项目B">
            <template #header>
              项目B 文件数：&nbsp;<el-tag>{{ projectInfo.ProjectB.FileLimit }}</el-tag>&nbsp;&nbsp;文件夹数：&nbsp;<el-tag type="danger">{{ projectInfo.ProjectB.DirLimit }}</el-tag>
              &nbsp;滚动高度&nbsp;<el-input-number :min="100" :max="1080" :step="20" v-model="data.ProjectBHeight" placeholder="高度" />px
            </template>
            <el-divider content-position="center">特有文件：<el-tag>{{ projectInfo.AddFileB.length }}</el-tag></el-divider>
            <el-row :style="`overflow-y: auto;height: ${data.ProjectBHeight}px;`" class="result">
              <template v-for="item,key in projectInfo.AddFileB" :key="key">
                <el-col :xs="18" :sm="18" :md="18" :lg="10" :xl="10"><el-tag type="warning" >{{ item.Name }}</el-tag></el-col>
                <el-col :xs="6" :sm="6" :md="6" :lg="4" :xl="4"><el-tag type="success">{{ Math.floor(item.Size / 1024 * 100) / 100 }}KB</el-tag></el-col>
                <el-col :xs="18" :sm="18" :md="18" :lg="6" :xl="6"><el-tag type="info">{{ new Date(item.UpdatedAt * 1000).toLocaleString() }}</el-tag></el-col>
                <el-col :xs="6" :sm="6" :md="6" :lg="4" :xl="4"><el-tag>{{ item.IsDir ? '文件夹' : '文件' }}</el-tag></el-col>
              </template>
            </el-row>
          </el-card>
        </el-col>
        <el-divider content-position="center">
          操作同步如下：<el-button :disabled="data.asyncValue.length == 0" size="small" type="primary" @click="asyncProject">同步</el-button>
        </el-divider>
        <el-col :span="24">
          <el-transfer
            v-model="data.asyncValue"
            :titles="['项目A', '项目B']"
            filterable
            :filter-method="filterMethod"
            filter-placeholder="请输入过滤名称"
            :data="projectInfo.transferData"
          />
        </el-col>
      </el-row>
    </template>
  </main>
</template>
<script lang="ts" setup>
import {onMounted, reactive,ref,shallowRef} from 'vue'
import {Greet,AsyncFile,GetFile} from '../../wailsjs/go/main/App'
import { ElMessage, type FormInstance,ElMessageBox } from 'element-plus'
import EditCode from "@/components/EditCode/index.vue"
const ruleFormRef = ref<FormInstance>()

const Options = {
  key: 0,
  label: '选项1',
  value: '选项1',
  dir: 0,
}

const defaultDataFileInfo = {
  IsDir: false,
  Name: "a.txt",
  Size: 1111,
  UpdatedAt: 1751547452,
};

const data = reactive({
  load: false,
  name: "",
  form: {
    pathA: '',
    pathB: '',
  },
  rules: {
    pathA: [
      { required: true, message: '请输入项目A路径', trigger: 'change' },
    ],
    pathB: [
      { required: true, message: '请输入项目B路径', trigger: 'change' },
    ],
  },
  ProjectView: false,
  ProjectAHeight: 400,
  ProjectBHeight: 400,
  asyncValue: [],
})

const projectInfo = reactive({
  ProjectA: {
    FileLimit: 166,
    DirLimit: 11,
  },
  AddFileA: Array(10).fill(defaultDataFileInfo),
  AddFileB: Array(10).fill(defaultDataFileInfo),
  ChangeFile: Array(10).fill(defaultDataFileInfo),
  ProjectB: {
    FileLimit: 166,
    DirLimit: 11,
  },
  transferData: [Options]
})

const languageOptions = {
  'javascript': 'JavaScript',
  'css': 'CSS',
  'html': 'HTML',
  'json': 'JSON',
}
const codeData = reactive({
  show: false,
  load: true,
  linesA: [],
  fileA: '',
  codeA: `const data = 2;
let a = data + 5;
function demo() {
  console.log(ddd)
}`,
  languageA: 'javascript',
  hideB: false,
  linesB: [],
  fileB: '',
  languageB: 'javascript',
  codeB: `const data = 2;
let a = data + 5;
function demo() {
  console.log(bbb)
}
const ddd = "ddd";`,
})

// 检测 代码是否一致
const changeCodePath = () => {
  if (!codeData.codeA || !codeData.codeB) {
    codeData.linesA = []
    codeData.linesB = []
    return 
  }
  const splitsA = codeData.codeA.split("\n")
  const splitsB = codeData.codeB.split("\n")
  if (!splitsA.length || !splitsB.length) {
    codeData.linesA = []
    codeData.linesB = []
    return 
  }

  const linesA = [];
  const linesB = [];
  if (splitsA.length >= splitsB.length) {
    for (let i = 0; i < splitsA.length; i++) {
      if (splitsB[i]) {
        if (splitsA[i] !== splitsB[i]) {
          linesA.push(i+1)
          linesB.push(i+1)
        }
      } else {
        linesA.push(i+1)
      }
    }
  } else {
    for (let i = 0; i < splitsB.length; i++) {
      if (splitsA[i]) {
        if (splitsA[i] !== splitsB[i]) {
          linesA.push(i+1)
          linesB.push(i+1)
        }
      } else {
        linesB.push(i+1)
      }
    }
  }
  codeData.linesA = linesA
  codeData.linesB = linesB
}

const onChangeProjectFile = (file:string , addFlag = false) => {
  codeData.show = true
  codeData.load = true
  codeData.fileA = file
  const language = file.split('.').pop()
  console.log(file, language)
  const keys = {
    'js': 'javascript',
    'json': 'json',
    'html': 'html',
    'css': 'css',
    'less': 'css',
    'scss': 'css',
  }
  let l = keys[language] || 'javascript'

  codeData.languageA = l
  
  
  if (addFlag) {
    codeData.hideB = true
    codeData.codeB = ''
  } else {
    codeData.hideB = false
    codeData.fileB = file
    codeData.languageB = l
  }

  ElMessage.info('加载中...')
  console.log('change file',addFlag,data.form.pathA + '/' + file,addFlag ? "" : data.form.pathB + file)
  GetFile(data.form.pathA + '/' + file,addFlag ? "" : data.form.pathB + file).then(result => {
    const resData = JSON.parse(result)
    ElMessage.success('加载成功')
    console.log(resData)
    setTimeout(() => {
      codeData.codeA = resData.data.fileA;
      codeData.codeB = resData.data.fileB;
      changeCodePath()

      codeData.load = false
    }, 500);
    
    // if (!addFlag) {
    //   codeData.codeB = resData.data.fileB
    //   console.log('更改文件', resData.data.fileB, resData.data.fileB.split("\n"))
    //   // changeCodePath()
    // }
  })
}

const filterMethod = (query: string, item: typeof Options) => {
  return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1
}

function greet() {
  Greet(data.form.pathA, data.form.pathB).then(result => {
    data.load = false
    const resData = JSON.parse(result)
    if (!resData || resData.code != 200)  {
      ElMessage.error(resData.msg || '操作失败')
      return ;
    }

    const res = resData.data
    data.ProjectView = true
    changeData(res)
    console.log(res)

  })
}

const asyncProject = () => {
  if (!data.asyncValue || !data.asyncValue.length){
    ElMessage.error('请选择同步文件')
    return 
  }
  ElMessageBox.confirm(
    '确认同步会将选中的文件直接复制到另一个项目，确保有备份(数据无价)，操作同步前自行备份数据 数据丢失概不负责。是否继续?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const strs:string[] = []
      console.log(data.asyncValue, projectInfo.transferData)
      data.asyncValue.forEach((item:any) => {
        strs.push(projectInfo.transferData[item-1].value)
      })
      console.log(data.form.pathA, data.form.pathB, strs.join(','))
      AsyncFile(data.form.pathA, data.form.pathB, strs.join(',')).then(result => {
        const resData = JSON.parse(result)
        if (!resData || resData.code != 200)  {
          ElMessage.error(resData.msg || '操作失败')
          return ;
        }
        console.log(result)
        ElMessage.success('同步成功')
        submitForm(ruleFormRef)
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功',
      })
    })
}

onMounted(()=> {
  // changeData(data)
  // changeCodePath()
  const pathA = window.localStorage.getItem('pathA')
  const pathB = window.localStorage.getItem('pathB')
  if (pathA && pathB) {
    data.form.pathA = pathA
    data.form.pathB = pathB
  }
})

// 处理数据
const changeData = (resData:any) => {
  if (!resData) return
  
  console.log(resData)
  projectInfo.AddFileA = resData.AddFileA ? resData.AddFileA : []
  projectInfo.AddFileB = resData.AddFileB ? resData.AddFileB : []
  projectInfo.ChangeFile = resData.ChangeFile ? resData.ChangeFile : []
  projectInfo.ProjectA.FileLimit = resData.ProjectA.FileLimit
  projectInfo.ProjectA.DirLimit = resData.ProjectA.DirLimit
  projectInfo.ProjectB.FileLimit = resData.ProjectB.FileLimit
  projectInfo.ProjectB.DirLimit = resData.ProjectB.DirLimit

  data.asyncValue = [];

  const transferDataArr = [Options]
  transferDataArr.shift()

  let key = -1

  key = 0
  transferDataArr.push(
  ...projectInfo.AddFileA.map((item:any) => {
    key++;
    return {
      key,
      label: `新增:${item.Name} ${item.IsDir ? '文件夹' : '文件'}`,
      value: item.Name,
      dir: item.IsDir ? 1 : 0,
    }
  })
  )

  transferDataArr.push(
  ...projectInfo.ChangeFile.map((item:any) => {
    key++;
    return {
      key,
      label: `修改:${item.Name} ${item.IsDir ? '文件夹' : '文件'}`,
      value: item.Name,
      dir: item.IsDir ? 1 : 0,
    }
  })
  )
  projectInfo.transferData = transferDataArr
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (!valid) {
      ElMessage.error('请检查输入项')
      return 
    }
    data.load = true
    data.form.pathA.indexOf('\\') >= 0 && (data.form.pathA = data.form.pathA.replace(/\\/g, '/'))
    data.form.pathB.indexOf('\\') >= 0 && (data.form.pathB = data.form.pathB.replace(/\\/g, '/'))
    greet()
    ElMessage.info('操作中...')
  })
}

const onSave = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (!valid) {
      ElMessage.error('请检查输入项')
      return 
    }
    window.localStorage.pathA = data.form.pathA
    window.localStorage.pathB = data.form.pathB
    ElMessage.success('保存成功')
  })
}
</script>
<style scoped>
.result .el-col {
  margin-bottom: 12px;
}
:deep(.el-transfer) {
  text-align: center;
}
:deep(.el-transfer-panel) {
  width: 40vw;
}
:deep(.el-transfer-panel__list) {
  height:50vh;
}
</style>
